<?php
	require 'connection.php';
	
	if(isset($_GET['action']))
	{
		switch($_GET['action'])
		{
			case 'login':
				{ 
					if(isset($_POST['user']) && isset($_POST['pass']))
					{
						if(!validateUser($_POST['user'], $_POST['pass'], $db_connect))
						{
							$_SESSION['error'] = "Invalid username or password! Try again!";
							unset($_GET['action']);
						}
					} else 
					{	
						$_SESSION['error'] = "Please enter a username and password.";
						unset($_GET['action']);
					}
				break;
				}

			case 'logout':
				{
					if(isLogged())
					{
						logout();
						echo "<div id='main'>";
						echo "<h2>Logged out!</h2>";
						echo "<a href='login.php'><input type='button' value='Back'></a>";
						echo "</div>";
						
					} else 
					{
						unset($_GET['action']);
					}
				break; 
				}
		}
 	}
?>
<html>
<head>
	<title>Login</title>
	<link type="text/css" href="style/form_css.css" rel="stylesheet"/>
</head>
<body>
<?php 
	if(isLogged())
	{
		echo "<div id='main'>";
		echo "<h2>Logged in!</h2>";
		echo "<h4>You are logged in as: ". $_SESSION['username'] . "</h4>"; 
		echo " <a href='index.php'><input type='button' value='Index'></a>";
		echo "<a href='login.php?action=logout'><input type='button' value='Logout'></a>";
		echo "</div>";
	}elseif(!isset($_GET['action']))
	{
		echo "<div id='main'>";
		echo "<h2>Login to the system</h2>";
		echo "<form name='login' method='post' action='login.php?action=login'>";
		echo "<p>Username: <input name='user'></p>";
		echo "<p>Password: <input type='password' name='pass'></p>";
		echo "<p><input type='submit' name='submit' value='Login!'></p>";
		echo "<a href='register.php'><input type='button' value='Register'></a>";
		echo "</div>";
	}
	
	echo "<div id='error'>";
	echo $_SESSION['error'];
	echo "</div>";
		
 ?>
 </body>
 </html>
 <?php 
	mysqli_close($db_connect);
?>